package com.xuchao.yao_jz.web.alibabapay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.xuchao.yao_jz.config.PayConfig;
import com.xuchao.yao_jz.dto.AlibabaPayDto;
import com.xuchao.yao_jz.entity.Order;
import com.xuchao.yao_jz.service.AlibabaPayService;
import com.xuchao.yao_jz.service.IOrderService;
import com.xuchao.yao_jz.vo.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alibaba")
@Slf4j
public class alibabaPayzhifuController {

    @Autowired
    AlibabaPayService alibabaPayService;
    @Autowired
    PayConfig payConfig;
    @Autowired
    IOrderService orderService;

    @RequestMapping("/createPayOrder")
    public ResultEntity createPayOrder(AlibabaPayDto alibabaPayDto) throws AlipayApiException {
        log.info("支付传参为:{}",JSON.toJSONString(alibabaPayDto));
        log.info("创建支付宝扫码订单开始订单号为:{}",alibabaPayDto.getOrderNo());

        if (alibabaPayDto != null){
            Order order = new Order();
            String str=alibabaPayDto.getYaopinname().substring(0,alibabaPayDto.getYaopinname().length()-1);
            order.setGroupname(str);
            order.setOrdernum(alibabaPayDto.getOrderNo());
            order.setPrice(alibabaPayDto.getSaleCount());
            boolean insert = orderService.addOrder(order);
        }

        log.info("根据orderNo:{}到redis 中查询二维码不存在开始调用支付宝的接口创建预支付订单......");
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",alibabaPayDto.getOrderNo());
        map.put("trade_no",alibabaPayDto.getOrderNo());
        map.put("total_amount","0.01");
        map.put("subject","Iphone6 16G");
        //商家id
        map.put("store_id","2016101900723724");
        map.put("timeout_express","7200m");
        AlipayTradePrecreateResponse qrCodePayOrder = alibabaPayService.createQrCodePayOrder(map);
        String qrcode = alibabaPayService.getAlibabaPayQRCode(qrCodePayOrder);
        log.info("创建支付宝扫码订单结束订单号为:{}",alibabaPayDto.getOrderNo());
        return ResultEntity.ok("创建支付宝扫码支付订单成功",qrcode);
    }




}
